package com.cloud.pikachu.storage.config;

import com.cloud.pikachu.storage.api.dto.StorageType;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

/**
 * 本地存储配置信息
 * @author ABug
 */
@Slf4j
@Component
public class LocalOssConfig extends OssConfig {

    public String newImageSavePath;
    /*
    本地存储保存的基础路径
     */
    @Value("${oss.local.basePath}")
    private String basePath;

    /*
    返回给调用者的图片路径前缀
     */
    @Value("${oss.local.requestImageUrlPrefix}")
    private String requestImageUrlPrefix;


    @Override
    public LocalOssResponse save(InputStream inputStream , String fileName , long saveDuration , int zipSize) throws OssException {
        LocalOssResponse localOssResponse = new LocalOssResponse();
        /*
        本地保存图片采用 双层目录结构
        基础路径/yyyy-MM-dd/hh/文件名称.jpg
         */

        if (newImageSavePath==null){
            log.info("初始化本地存储目录");
            String newFilePath = new SimpleDateFormat("yyyy-MM-dd/HH").format(new Date()) + File.separator;
            newImageSavePath = newFilePath;
            File file = new File(basePath + newFilePath);
            if(!file.exists()){
                file.mkdirs();
            }
        }
        /*
        判断是否需要进行压缩处理
        todo ABug 暂不支持压缩
         */
        if(zipSize>0){
            throw new OssException("暂不支持压缩保存方式");
        }

        String saveFileName = System.currentTimeMillis()+((int)(Math.random()*10000))+ "-" + fileName;
        String relativePathAndFileName = newImageSavePath + saveFileName;
        String allFilePathAndName = basePath + relativePathAndFileName;
        File file = new File(allFilePathAndName);
        try {
            FileUtils.copyInputStreamToFile(inputStream , file);

            localOssResponse.setFileUrlPath(requestImageUrlPrefix + relativePathAndFileName);
            localOssResponse.setDiyHreads(new HashMap<>());
            localOssResponse.setSaveDuration(saveDuration);
            localOssResponse.setSaveType(StorageType.OSS_LOCALHOST.getKey());
            localOssResponse.setFileSize(file.length());
        } catch (IOException e) {
            log.error("IOException异常，文件保存时异常..." , e);
            throw new OssException("IOException异常，文件保存时异常...");
        }finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                log.error("IOException异常，关闭文件流失败..." , e);
                throw new OssException("IOException异常，关闭文件流失败...");
            }
        }

        return localOssResponse;
    }
}
